package com.lagou.demo;

import com.lagou.mapper.OrdersMapper;
import com.lagou.mapper.UserMapper;
import com.lagou.pojo.Order;
import com.lagou.pojo.Role;
import com.lagou.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest {

    private UserMapper userMapper;
    private OrdersMapper ordersMapper;
    private SqlSession sqlSession;

    @Before
    public void before() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = build.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
        ordersMapper = sqlSession.getMapper(OrdersMapper.class);
    }

    @After
    public void after() {
        sqlSession.close();
    }

    @Test
    public void findById() throws IOException {
        User user = userMapper.findById(1);
        System.out.println(user);
    }

    @Test
    public void findByCondition() {
        User user = new User();
        user.setId(2);
        user.setUsername("tom");
        user = userMapper.findByCondition(user);
        System.out.println(user);
        user = new User();
        user.setUsername("lucy");
        user = userMapper.findByCondition(user);
        System.out.println(user);
    }

    @Test
    public void findByIds() {
        Integer[] ids = new Integer[]{1,2};
        List<User> users = userMapper.findByIds(ids);
        users.forEach(user -> System.out.println(user));
    }

    @Test
    public void findAllInfo() {
        List<Order> orders = ordersMapper.findAllInfo();
        orders.forEach(order -> System.out.println(order));
    }

    @Test
    public void findAll() {
        List<User> users = userMapper.findAll();
        users.forEach(user -> {
            System.out.println(user.getUsername());
            List<Order> orders = user.getOrderList();
            orders.forEach(order -> System.out.println(order));
            System.out.println("----------------------------------");
        });
    }

    @Test
    public void findAllUserAndRole() {
        List<User> users = userMapper.findAllUserAndRole();
        users.forEach(user -> {
            System.out.println(user);
            List<Role> roles = user.getRoleList();
            roles.forEach(role -> System.out.println(role));
            System.out.println("----------------------------------");
        });
    }
}
